package service

// comment.go
// Comment 相关的业务逻辑

import (
	"errors"
	"gforum/global"
	"gforum/model"
	"github.com/go-sql-driver/mysql"
	"strconv"
)

// PostComment post comment to given post by post id
func PostComment(postID string, content model.Comment) (*model.Comment, error) {

	{
		// 低能完了:(
		// TODO: 优化
		postIDFromStr, _ := strconv.Atoi(postID)
		content.PostID = uint(postIDFromStr)
	}

	err := global.Db.Create(&content).Error
	var sqlErr *mysql.MySQLError
	if errors.As(err, &sqlErr) {
		switch sqlErr.Number {
		case 1452:
			return nil, ErrRecordNotFound
		default:
			return nil, err
		}
	} else if err != nil {
		return nil, err
	}

	var postedComment model.Comment
	err = global.Db.
		Where("id = ?", content.ID).
		Find(&postedComment).Error // 这里的 content 在类型上实际上是 Comment 实例，所以通过 Comment.ID 来查询完整的 Comment 实例
	if err != nil {
		return nil, err
	}

	return &postedComment, nil
}

// UpdateComment update comment with given comment id
func UpdateComment(commentID string, content model.Comment) (*model.Comment, error) {
	result := global.Db.Model(&model.Comment{}).Where("id = ?", commentID).Updates(&content)
	if result.RowsAffected == 0 {
		return nil, ErrRecordNotFound
	}
	if result.Error != nil {
		return nil, result.Error
	}

	var updatedComment model.Comment
	err := global.Db.Where("id = ?", commentID).Find(&updatedComment).Error
	if err != nil {
		return nil, err
	}

	return &updatedComment, nil
}

// DeleteCommentByID delete comment with given comment ID.
// Permission to delete comment was checked in middlewares.EditPermissionRequired
func DeleteCommentByID(commentID string) error {
	result := global.Db.Where("id = ?", commentID).Delete(&model.Comment{})
	if result.Error != nil {
		return result.Error
	} else if result.RowsAffected == 0 {
		return ErrRecordNotFound
	}
	return nil
}

// GetAllCommentsByPostID get all comments by post ID with pagination
func GetAllCommentsByPostID(postID string, query model.Pagination) (*[]model.Comment, error) {
	var comments []model.Comment
	err := global.Db.
		Where("post_id = ?", postID).
		Offset((query.Page - 1) * query.Size).
		Limit(query.Size).
		Find(&comments).Error
	if err != nil {
		return nil, err
	}

	return &comments, nil
}

// GetUserCommentsByID get all comments by user ID with pagination
func GetUserCommentsByID(userID string, query model.Pagination) (*[]model.Comment, error) {
	var comments []model.Comment
	err := global.Db.
		Where("user_id = ?", userID).
		Offset((query.Page - 1) * query.Size).
		Limit(query.Size).
		Find(&comments).Error
	if err != nil {
		return nil, err
	}

	return &comments, nil

}
